<template>
  <div class="system-edit-menu-container">
    <el-tree-select
        ref="departmentTreeRef"
        filterable
        v-model="department_id"
        v-bind="attrs"
        :data="departmentTreeData"
        :props="{label: 'name', value: 'id',children:'children'}"
        check-strictly
        :render-after-expand="false"
        @change="getList"
    />
  </div>
</template>

<script setup name="DepartmentTree">
import {computed, onMounted, reactive, ref, useAttrs, watch} from 'vue';
import {departmentApi} from "/@/api/hrms/department"

const departmentTreeRef = ref()
const attrs = useAttrs()

const props = defineProps({
  departmentList: {
    type: Array,
    default: () => []
  }, department_id: {
    type: String,
    default: () => null
  }
})

// 树结构
const departmentTreeData = computed(() => {
  console.log('组织数据：', state.allDepartmentTreeList)
  return [{name: '根目录2', id: null, children: [...state.allDepartmentTreeList]}]
})

// 递归组装
const departmentAssembly = (parent_department, all_department) => {
  // console.log('父级组织：', parent_department)
  parent_department.forEach((parent) => {
    all_department.forEach((department) => {
      if (department.parent_id === parent.id) {
        parent.children = parent.children ? parent.children : [];
        parent.children.push(department);
      }
    })
    if (parent.children) departmentAssembly(parent.children, all_department);
  })
  state.allDepartmentTreeList = parent_department
};
// 获取组织数
const getList = async () => {
  // departmentTreeRef.value.openLoading()
  let res = await departmentApi().allDepartmentList({})
  // state.allDepartmentTreeList = res.data
  let parent_department = []
  if (res.data.length > 0) {
    res.data.forEach((department) => {
      if (!department.parent_id) {
        parent_department.push(department)
      }
    })
    departmentAssembly(parent_department, res.data)
  }
  // departmentTreeRef.value.closeLoading()
};


const state = reactive({
  isShowDialog: false,
  editType: '',
  // 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由组织格式
  rules: {
    name: [{required: true, message: '请输入组织名称', trigger: 'blur'},],
    // parent_id: [{required: true, message: '请选择上级组织', trigger: 'blur'},]
  },
  menuData: [], // 上级组织数据
  allDepartmentTreeList: [],
  department_id: null
});


const emits = defineEmits([
  "update:modelValue", "change",
])

watch(
    () => props.department_id,
    () => {
    },
    {deep: true}
)

let department_id = computed({
  get() {
    return props.department_id
  },
  set(val) {
    emits('update:modelValue', val)
  }
})
// 页面加载时
onMounted(() => {
  getList();
});


</script>
